package com.mgblog.web.action;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.mgblog.service.inter.ArticleServiceInter;
import com.mgblog.service.inter.ArticleSortServiceInter;
import com.mgblog.service.inter.UserServiceInter;
import com.mgblog.utils.LogUtil;
import com.mgblog.utils.Pager;
import com.mgblog.utils.Tools;
import com.mgblog.vo.Article;
import com.mgblog.vo.ArticleSort;
import com.mgblog.vo.User;
import com.opensymphony.xwork2.ActionContext;

@Controller
public class NoCheckAction {
	private User user;
	private static Pager page = new Pager();
	@Resource
	private UserServiceInter userService;
	@Resource
	private ArticleServiceInter articleService;
	@Resource
	private ArticleSortServiceInter articelSortService;
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	/**
	 * 用户登陆
	 * @return
	 */
	public String login(){
		if(null != user){
			User loginUser = userService.login(user);
			if(null != loginUser){
				ActionContext.getContext().getSession().put(Tools.LOGIN_USER, loginUser);
			}else{
				//登陆失败
			}
		}
		return toIndex();
	}
	/**
	 * 退出系统
	 * @return
	 */
	public String logout(){
		ActionContext.getContext().getSession().remove(Tools.LOGIN_USER);
		return toIndex();
	}
	/**
	 * 全局跳转到首页
	 * @return
	 */
	public String toIndex(){
		//分页取出文章page
		HttpServletRequest request = ServletActionContext.getRequest();
		String sortId = request.getParameter("sortId");
		int currentPage=1;
		if(request.getParameter("currentPage")!=null){
			currentPage=Integer.parseInt(request.getParameter("currentPage").toString());
		}
		if(null != sortId){
			//按分类来显示文章并分页
			getArticlePageBySort(sortId, currentPage);
		}else{
			//所有文章并分页
			getAllArticlePage(request,currentPage);
		}
		ActionContext.getContext().put("page", page);
		//所有分类放到request中
		getAllSorts("id asc");
		
		return "index";
	}
	/**
	 * 存储所有分类
	 * @param order 排序借口
	 */
	private void getAllSorts(String order) {
		//得到所有的文章分类按时间排序desc
		ActionContext.getContext().put("sortList", articelSortService.getAllArticleSorts(order));
	}
	/**
	 * 按分类显示文章的分页
	 * @param sortId
	 * @param currentPage
	 */
	private void getArticlePageBySort(String sortId, int currentPage) {
		//得到分类下的文章总行数
		ArticleSort as = articelSortService.getArticleSortById(Integer.parseInt(sortId.trim()));
		int totalCount = as.getArticleNum();
		//处理页数越界问题
		int totalPage = Tools.getArticlePageBySortTotal(totalCount);
		if(currentPage > totalPage){
			currentPage = totalPage;
		}
		page.paging(currentPage, Tools.ARTICLE_BY_SORT_PAGE_SIZE, totalCount);
		page = articleService.findArticlePageByArticle(page,"addTime desc",as);
		//将as文章分类放到request中，可能会用
		ActionContext.getContext().put("aSort", as);
	}
	/**
	 * 得到所有的文章并分页
	 * @param request
	 */
	private void getAllArticlePage(HttpServletRequest request,int currentPage) {
		
		//得到Article的总行数
		int totalCount=articleService.count();
		//处理页数越界问题
		int totalPage = Tools.getArticlePageTotal(totalCount);
		if(currentPage > totalPage){
			currentPage = totalPage;
		}
		page.paging(currentPage, Tools.ARTICLE_PAGE_SIZE, totalCount);
		page = articleService.findArticlePage(page,"addTime desc");
	}
	/**
	 * 显示文章详情
	 * @return 跳转到showArticle视图
	 */
	public String showArticle(){
		String str_id = ServletActionContext.getRequest().getParameter("id");
		Article a = articleService.findArticleById(Integer.parseInt(str_id.trim()));
		ActionContext.getContext().put("article", a);
		return "showArticle";
	}
	/**
	 * ajax来完成升序降序，后台响应，返回json数据
	 */
	public String orderBy(){
		String _order = ServletActionContext.getRequest().getParameter("order");
		System.out.println(_order);
		List<ArticleSort> sorts = articelSortService.getAllArticleSorts(_order);
		//利用json.jar来转list为json---处理json转换死循环
		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(false);      
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); 
		config.setExcludes(new String[]{//只要设置这个数组，指定过滤哪些字段。   
				  "user",
				  "articleSet"
				});   
		String json = JSONSerializer.toJSON(sorts,config).toString();
		LogUtil.logger.info(json);
		try {
			ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
			out.write(json.getBytes());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
